package com.sanjin.configuration.security;

import com.alibaba.fastjson.JSON;
import com.sanjin.enums.ResponseEnum;
import com.sanjin.utils.ResponseVoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description: 未认证处理
 * @author: sanjin
 * @date: 2019/5/6 9:15
 */
@Slf4j
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 访问需要进行认证接口，如果没有进行认证，会执行到该方法
        log.info("认证失败：" + authException.getMessage());
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        String body = JSON.toJSONString(ResponseVoUtils.error(ResponseEnum.AUTHENTICATEERROR));


        printWriter.write(body);
        printWriter.flush();
    }
}
